//
//  QcBaseTypeController.m
//  QcMedical1
//
//  Created by jiawen Du on 2016/12/23.
//  Copyright © 2016年 jiawen Du. All rights reserved.
//

#import "QcBaseTypeController.h"
#import "NetWorkManager.h"
#import "NSString+pinyin.h"
#import "QMQCIllDetailModel.h"

#define kcindex @"index"

@interface QcBaseTypeController ()<UITableViewDelegate,UITableViewDataSource>

//tableView
@property (nonatomic, strong) UITableView *tableview;

@property(nonatomic,strong)NSArray *catalogueModelList;



@property (nonatomic, weak) UITextField *search;

@property (nonatomic, strong) NSArray *illDetailArray;

@property (nonatomic, strong) NSMutableArray *illUserArray;

@property (nonatomic, assign) BOOL isSearchState;

@end


static NSString *caseTypeCell = @"dd";
@implementation QcBaseTypeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    
    [self setupUI];
    
    [self getData];
}


- (void)getData {
    
    /*
     //#疾病细分接口-------------------------------------------------
     // 肿瘤     ci1_id = 1
     // 心血管   ci1_id = 2
     // 神经科   ci1_id = 3
     // 血液科   ci1_id = 4
     // 骨科     ci1_id = 5
     // 公益活动  ci1_id = 6
     */
//    
    [[NetWorkManager sharedManager]loadDiseaseSubWithCi_id:_cil_id page:15 successBlock:^(NSArray *caseArray) {
        
        self.catalogueModelList = caseArray;
        [self.tableview reloadData];
        
    } errorBlock:^(NSString *error) {
        
        
        
    }];
    
}

- (void)loadData
{
    
    
    NSString *urlString = kSearchCI3Url;
    NSDictionary *dic = @{
                          @"page_size":@15,
                          @"page":@1,
                          @"ci1_id":@(_cil_id),
                          @"keyword":@""
                          };
    [[NetWorkTool shareManager] POST_RequestWithUrlString:urlString parmas:dic successBloock:^(id responseObject) {
        
        NSArray *array = responseObject[@"data"];
        
        NSArray *detailArray = [NSArray array];
        detailArray = [NSArray yy_modelArrayWithClass:[QMQCIllDetailModel class] json:array];
        
        NSMutableArray *nameArr = [NSMutableArray array];
        
        for (int i = 0; i < detailArray.count; i++) {
            
            QMQCIllDetailModel *model = detailArray[i];
            
            NSString *name = model.ci3_name;
            
            [nameArr addObject:name];
        }
        
        NSMutableArray *illDetailArray = [NSMutableArray array];
        
        for (int i = 0; i < nameArr.count; ++i) {
            
            QMQCIllDetailModel *dto = [[QMQCIllDetailModel alloc] init];
            
            //转拼音
            NSString *PinYin =  [nameArr[i] transformToPinyin];
            
            //首字母
            NSString *FirstLetter = [nameArr[i] transformToPinyinFirstLetter];
            
            //        NSLog(@"pinyin = %@ -- %@",PinYin,FirstLetter);
            
            dto.ci3_name = nameArr[i];
            dto.namePinYin = PinYin;
            dto.nameFirstLetter = FirstLetter;
            
            [illDetailArray addObject:dto];
        }
        self.illDetailArray = illDetailArray.copy;
        
        [self.tableview reloadData];
        
        
    } failureBlock:^(NSError *error) {
        
    }];
}

- (void)setupUI {
    
    //搜索栏
    UITextField *searchTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
    
    [self.navigationItem setTitleView:searchTF];
    
    self.search = searchTF;
    
    searchTF.placeholder = @"请输入您要搜索的项目";
    
    searchTF.backgroundColor = [UIColor whiteColor];
    
    searchTF.borderStyle = UITextBorderStyleRoundedRect;
    
    
    
    
     self.navigationItem.title = @"疾病细分";
    

    //tableView
    UITableView *tableView = [[UITableView alloc]init];
    
    self.tableview = tableView;
    
    tableView.delegate = self;
    
    tableView.dataSource = self;
    
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
        
    }];
    
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:caseTypeCell];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
}
/** 监听 */
- (void)textChange:(NSNotification *)note{
    
    UITextField *textField = (UITextField *)[note object];
    
    //如果项目大，搜索的地方多，就要使用多线程，然后在刷新tableview的时候，回到主线程
    [self startSearch:textField.text];
}
-(void)startSearch:(NSString *)string{
    
    if (self.illUserArray.count>0) {
        
        [self.illUserArray removeAllObjects];
    }
    
    //开始搜索
    NSString *key = string.lowercaseString;
    NSMutableArray *tempArr = [NSMutableArray array];
    
  //  NSLog(@"key = %@",key);
    
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        [self.illDetailArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            QMQCIllDetailModel *dto = self.illDetailArray[idx];
            
            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = dto.ci3_name.lowercaseString;
            NSString *namePinyin = dto.namePinYin.lowercaseString;
            NSString *nameFireLetter = dto.nameFirstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            if (rang1.length>0) { ///比牛 -比
                
                [tempArr addObject:dto];
            }else{
                
                if ([nameFireLetter containsString:key]) { //bn - b
                    
                    [tempArr addObject:dto];
                    
                }else{  //ershou
                    
                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key] ) {
                            [tempArr addObject:dto];
                        }
                    }
                }
            }
        }];
        
        NSMutableArray *userArray = [NSMutableArray array];
        
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.illUserArray containsObject:tempArr[idx]]) {
                
                [userArray addObject:tempArr[idx]];
            //    NSLog(@"self.searchResultList  = %@",userArray);
                
            }
        }];
        
        self.illUserArray = userArray;
        
    //    NSLog(@"self.searchResultList  = %@",self.illUserArray);
        self.isSearchState = YES;
    }else{
        
        self.isSearchState = NO;
    }
    
    [self.tableview reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    UILabel *noResultLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    
    noResultLab.font = [UIFont systemFontOfSize:20];
    noResultLab.textColor = [UIColor lightGrayColor];
    noResultLab.textAlignment = NSTextAlignmentCenter;
    noResultLab.hidden = YES;
    noResultLab.text = @"抱歉！没有搜索到相关数据";
    tableView.backgroundView = noResultLab;
    
    
    if (_isSearchState) {
        
        if (self.illUserArray.count > 0) {
            
            noResultLab.hidden = YES;
            
            return self.illUserArray.count;
            
        }else{
            
            noResultLab.hidden = NO;
            
            return 0;
        }
    }else{
        
        return self.illDetailArray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:caseTypeCell forIndexPath:indexPath];
    
    cell.accessoryType = UITableViewCellEditingStyleDelete;
    
    QMQCIllDetailModel *dto = nil;
    
    if (_isSearchState) {
        
        dto = self.illUserArray[indexPath.row];
    }else{
        
        dto = self.illDetailArray[indexPath.row];
    }
    
    cell.textLabel.text = dto.ci3_name;
    cell.textLabel.font = [UIFont fontWithName:@"DiwanMishafi" size:18];
    cell.textLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:18];
    return cell;
    

    
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    UITableViewCell *cell = self.tableView.visibleCells[indexPath.row];
//    if (_detailBlock) {
//        
//        _detailBlock(cell.textLabel.text);
//    }
//    
//    [self.navigationController popViewControllerAnimated:YES];
//}



//-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    
//    return self.catalogueModelList.count;
//}

//-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:caseTypeCell forIndexPath:indexPath];
//    
//    QcCaseChooseModel *caseM = self.illDetailArray[indexPath.row];
//    
//    cell.textLabel.text = caseM.ci3_name;
//    cell.textLabel.font = [UIFont fontWithName:@"CloudShuiZhuGBK" size:15];
//    return cell;
//    
//}

#define kcaseinfo @"caseinfo"
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QcCaseChooseModel *caseM = self.catalogueModelList[indexPath.row];
    
    NSString *infoText = caseM.ci3_name;
    
    //发通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kcaseinfo object:infoText];
    
    [self.navigationController popViewControllerAnimated:YES];

}



@end
